/*
 * This file is part of CompetitionGenerator.
 * CompetitionGenerator is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * CompetitionGenerator is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * 
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with CompetitionGenerator. If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * CompetitionForm.java
 *
 * Created on 28-may-2009, 15:31:41
 */
package competitiongenerator.forms;

import competitiongenerator.entities.SortedListModel;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;

/**
 * CompetitionForm class.
 * @author Ashitaka
 * @date 28-05-2009
 */
public class CompetitionForm extends javax.swing.JDialog {

    /** Logger. */
    private static final Logger logger = Logger.getLogger(CompetitionForm.class.getName());
    /** DefaultListModel for the JList management. */
    private DefaultListModel unsortedModel;
    /** SortedListModel for the JList management in a sorted way. */
    private SortedListModel sortedModel;

    /** 
     * Creates new form CompetitionForm.
     */
    public CompetitionForm(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        unsortedModel = new DefaultListModel();
        sortedModel = new SortedListModel(unsortedModel);
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        MainBodyPanel = new javax.swing.JPanel();
        NameLabel = new javax.swing.JLabel();
        NameTextField = new javax.swing.JTextField();
        RadioButtonPanel = new javax.swing.JPanel();
        OneDayRadioButton = new javax.swing.JRadioButton();
        ThreeDayRadioButton = new javax.swing.JRadioButton();
        FiveDayRadioButton = new javax.swing.JRadioButton();
        OtherRadioButton = new javax.swing.JRadioButton();
        InitDateLabel = new javax.swing.JLabel();
        InitDateSpinner = new javax.swing.JSpinner(new SpinnerDateModel());
        EndDateLabel = new javax.swing.JLabel();
        EndDateSpinner = new javax.swing.JSpinner(new SpinnerDateModel());
        RegionLabel = new javax.swing.JLabel();
        RegionTextField = new javax.swing.JTextField();
        CountryLabel = new javax.swing.JLabel();
        CountryTextField = new javax.swing.JTextField();
        LocationTextField = new javax.swing.JTextField();
        CategoryPanel = new javax.swing.JPanel();
        CategoryScrollPane = new javax.swing.JScrollPane();
        CategoryList = new javax.swing.JList();
        AddCategoryButton = new javax.swing.JButton();
        AddCategoryTextField = new javax.swing.JTextField();
        EditCategoryButton = new javax.swing.JButton();
        EditCategoryTextField = new javax.swing.JTextField();
        DeleteCategoryButton = new javax.swing.JButton();
        CountryLabel1 = new javax.swing.JLabel();
        AcceptButton = new javax.swing.JButton();
        CancelButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(competitiongenerator.CompetitionGeneratorApp.class).getContext().getResourceMap(CompetitionForm.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N
        setResizable(false);

        MainBodyPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("MainBodyPanel.border.title"))); // NOI18N
        MainBodyPanel.setName("MainBodyPanel"); // NOI18N

        NameLabel.setText(resourceMap.getString("NameLabel.text")); // NOI18N
        NameLabel.setName("NameLabel"); // NOI18N

        NameTextField.setName("NameTextField"); // NOI18N

        RadioButtonPanel.setName("RadioButtonPanel"); // NOI18N

        buttonGroup1.add(OneDayRadioButton);
        OneDayRadioButton.setSelected(true);
        OneDayRadioButton.setText(resourceMap.getString("OneDayRadioButton.text")); // NOI18N
        OneDayRadioButton.setActionCommand(resourceMap.getString("OneDayRadioButton.actionCommand")); // NOI18N
        OneDayRadioButton.setName("OneDayRadioButton"); // NOI18N
        OneDayRadioButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                OneDayRadioButtonActionPerformed(evt);
            }
        });

        buttonGroup1.add(ThreeDayRadioButton);
        ThreeDayRadioButton.setText(resourceMap.getString("ThreeDayRadioButton.text")); // NOI18N
        ThreeDayRadioButton.setActionCommand(resourceMap.getString("ThreeDayRadioButton.actionCommand")); // NOI18N
        ThreeDayRadioButton.setName("ThreeDayRadioButton"); // NOI18N
        ThreeDayRadioButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ThreeDayRadioButtonActionPerformed(evt);
            }
        });

        buttonGroup1.add(FiveDayRadioButton);
        FiveDayRadioButton.setText(resourceMap.getString("FiveDayRadioButton.text")); // NOI18N
        FiveDayRadioButton.setActionCommand(resourceMap.getString("FiveDayRadioButton.actionCommand")); // NOI18N
        FiveDayRadioButton.setName("FiveDayRadioButton"); // NOI18N
        FiveDayRadioButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                FiveDayRadioButtonActionPerformed(evt);
            }
        });

        buttonGroup1.add(OtherRadioButton);
        OtherRadioButton.setText(resourceMap.getString("OtherRadioButton.text")); // NOI18N
        OtherRadioButton.setActionCommand(resourceMap.getString("OtherRadioButton.actionCommand")); // NOI18N
        OtherRadioButton.setName("OtherRadioButton"); // NOI18N
        OtherRadioButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                OtherRadioButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout RadioButtonPanelLayout = new javax.swing.GroupLayout(RadioButtonPanel);
        RadioButtonPanel.setLayout(RadioButtonPanelLayout);
        RadioButtonPanelLayout.setHorizontalGroup(
            RadioButtonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(RadioButtonPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(OneDayRadioButton, javax.swing.GroupLayout.DEFAULT_SIZE, 108, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(ThreeDayRadioButton, javax.swing.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(FiveDayRadioButton, javax.swing.GroupLayout.DEFAULT_SIZE, 114, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(OtherRadioButton, javax.swing.GroupLayout.DEFAULT_SIZE, 96, Short.MAX_VALUE)
                .addContainerGap())
        );
        RadioButtonPanelLayout.setVerticalGroup(
            RadioButtonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(RadioButtonPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(RadioButtonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(OneDayRadioButton)
                    .addComponent(ThreeDayRadioButton)
                    .addComponent(FiveDayRadioButton)
                    .addComponent(OtherRadioButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        InitDateLabel.setText(resourceMap.getString("InitDateLabel.text")); // NOI18N
        InitDateLabel.setName("InitDateLabel"); // NOI18N

        InitDateSpinner.setName("InitDateSpinner"); // NOI18N
        JSpinner.DateEditor de = new JSpinner.DateEditor(InitDateSpinner, "dd/MM/yyyy");
        InitDateSpinner.setEditor(de);
        Date today = new Date();
        Calendar aux = new GregorianCalendar();
        aux.setTime(today);
        aux.set(Calendar.HOUR, 0);
        aux.set(Calendar.MINUTE, 0);
        aux.set(Calendar.SECOND, 0);
        today = aux.getTime();
        InitDateSpinner.setValue(today);
        InitDateSpinner.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                InitDateSpinnerStateChanged(evt);
            }
        });

        EndDateLabel.setText(resourceMap.getString("EndDateLabel.text")); // NOI18N
        EndDateLabel.setName("EndDateLabel"); // NOI18N

        EndDateSpinner.setEnabled(false);
        EndDateSpinner.setName("EndDateSpinner"); // NOI18N
        EndDateSpinner.setValue(EndDateSpinner.getValue());
        JSpinner.DateEditor de2 = new JSpinner.DateEditor(EndDateSpinner, "dd/MM/yyyy");
        EndDateSpinner.setEditor(de2);
        EndDateSpinner.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                EndDateSpinnerStateChanged(evt);
            }
        });

        RegionLabel.setText(resourceMap.getString("RegionLabel.text")); // NOI18N
        RegionLabel.setName("RegionLabel"); // NOI18N

        RegionTextField.setName("RegionTextField"); // NOI18N

        CountryLabel.setText(resourceMap.getString("CountryLabel.text")); // NOI18N
        CountryLabel.setName("CountryLabel"); // NOI18N

        CountryTextField.setName("CountryTextField"); // NOI18N

        LocationTextField.setText(resourceMap.getString("LocationTextField.text")); // NOI18N
        LocationTextField.setName("LocationTextField"); // NOI18N

        CategoryPanel.setName("CategoryPanel"); // NOI18N

        CategoryScrollPane.setName("CategoryScrollPane"); // NOI18N

        CategoryList.setModel(sortedModel);
        CategoryList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        CategoryList.setToolTipText(resourceMap.getString("CategoryList.toolTipText")); // NOI18N
        CategoryList.setName("CategoryList"); // NOI18N
        CategoryList.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                CategoryListKeyPressed(evt);
            }
        });
        CategoryScrollPane.setViewportView(CategoryList);

        AddCategoryButton.setText(resourceMap.getString("AddCategoryButton.text")); // NOI18N
        AddCategoryButton.setName("AddCategoryButton"); // NOI18N
        AddCategoryButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AddCategoryButtonActionPerformed(evt);
            }
        });

        AddCategoryTextField.setText(resourceMap.getString("AddCategoryTextField.text")); // NOI18N
        AddCategoryTextField.setName("AddCategoryTextField"); // NOI18N
        AddCategoryTextField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                AddCategoryTextFieldKeyPressed(evt);
            }
        });

        EditCategoryButton.setText(resourceMap.getString("EditCategoryButton.text")); // NOI18N
        EditCategoryButton.setName("EditCategoryButton"); // NOI18N
        EditCategoryButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                EditCategoryButtonActionPerformed(evt);
            }
        });

        EditCategoryTextField.setEditable(false);
        EditCategoryTextField.setText(resourceMap.getString("EditCategoryTextField.text")); // NOI18N
        EditCategoryTextField.setName("EditCategoryTextField"); // NOI18N
        EditCategoryTextField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                EditCategoryTextFieldKeyPressed(evt);
            }
        });

        DeleteCategoryButton.setText(resourceMap.getString("DeleteCategoryButton.text")); // NOI18N
        DeleteCategoryButton.setName("DeleteCategoryButton"); // NOI18N
        DeleteCategoryButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DeleteCategoryButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout CategoryPanelLayout = new javax.swing.GroupLayout(CategoryPanel);
        CategoryPanel.setLayout(CategoryPanelLayout);
        CategoryPanelLayout.setHorizontalGroup(
            CategoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(CategoryPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(CategoryScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 224, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(CategoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(DeleteCategoryButton)
                    .addGroup(CategoryPanelLayout.createSequentialGroup()
                        .addGroup(CategoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(AddCategoryButton)
                            .addComponent(EditCategoryButton))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(CategoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(EditCategoryTextField)
                            .addComponent(AddCategoryTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 238, Short.MAX_VALUE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        CategoryPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {AddCategoryButton, DeleteCategoryButton, EditCategoryButton});

        CategoryPanelLayout.setVerticalGroup(
            CategoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(CategoryPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(CategoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(CategoryScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 250, Short.MAX_VALUE)
                    .addGroup(CategoryPanelLayout.createSequentialGroup()
                        .addGroup(CategoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(AddCategoryButton)
                            .addComponent(AddCategoryTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(CategoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(EditCategoryButton)
                            .addComponent(EditCategoryTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(DeleteCategoryButton)))
                .addContainerGap())
        );

        CountryLabel1.setText(resourceMap.getString("CountryLabel1.text")); // NOI18N
        CountryLabel1.setName("CountryLabel1"); // NOI18N

        javax.swing.GroupLayout MainBodyPanelLayout = new javax.swing.GroupLayout(MainBodyPanel);
        MainBodyPanel.setLayout(MainBodyPanelLayout);
        MainBodyPanelLayout.setHorizontalGroup(
            MainBodyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(MainBodyPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(MainBodyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(MainBodyPanelLayout.createSequentialGroup()
                        .addGroup(MainBodyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(MainBodyPanelLayout.createSequentialGroup()
                                .addGap(8, 8, 8)
                                .addGroup(MainBodyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(CountryLabel)
                                    .addComponent(CountryLabel1)
                                    .addComponent(NameLabel)))
                            .addComponent(InitDateLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(MainBodyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(MainBodyPanelLayout.createSequentialGroup()
                                .addGroup(MainBodyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(MainBodyPanelLayout.createSequentialGroup()
                                        .addComponent(InitDateSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(74, 74, 74))
                                    .addComponent(CountryTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 168, Short.MAX_VALUE))
                                .addGap(28, 28, 28)
                                .addGroup(MainBodyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(EndDateLabel, javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(RegionLabel, javax.swing.GroupLayout.Alignment.TRAILING))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(MainBodyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(EndDateSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(RegionTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(84, 84, 84))
                            .addComponent(LocationTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(NameTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 504, Short.MAX_VALUE)
                            .addComponent(RadioButtonPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addComponent(CategoryPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        MainBodyPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {EndDateSpinner, InitDateSpinner});

        MainBodyPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {CountryTextField, LocationTextField, RegionTextField});

        MainBodyPanelLayout.setVerticalGroup(
            MainBodyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(MainBodyPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(MainBodyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(NameLabel)
                    .addGroup(MainBodyPanelLayout.createSequentialGroup()
                        .addComponent(NameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(RadioButtonPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(MainBodyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(InitDateSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(InitDateLabel)
                            .addComponent(EndDateSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(EndDateLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(MainBodyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(CountryTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(CountryLabel)
                            .addComponent(RegionLabel)
                            .addComponent(RegionTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(MainBodyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(LocationTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(CountryLabel1))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(CategoryPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        MainBodyPanelLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {CountryLabel, CountryLabel1, CountryTextField, EndDateLabel, EndDateSpinner, InitDateLabel, InitDateSpinner, LocationTextField, NameLabel, NameTextField, RegionTextField});

        AcceptButton.setText(resourceMap.getString("AcceptButton.text")); // NOI18N
        AcceptButton.setName("AcceptButton"); // NOI18N
        AcceptButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AcceptButtonActionPerformed(evt);
            }
        });

        CancelButton.setText(resourceMap.getString("CancelButton.text")); // NOI18N
        CancelButton.setName("CancelButton"); // NOI18N
        CancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CancelButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(468, Short.MAX_VALUE)
                .addComponent(AcceptButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(CancelButton)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(MainBodyPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(16, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(MainBodyPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(CancelButton)
                    .addComponent(AcceptButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Manages the OneDayRadioButton ActionPerformed.
     * @param evt
     */
    private void OneDayRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OneDayRadioButtonActionPerformed
        // Check if the second spinner is enabled
        if (EndDateSpinner.isEnabled()) {
            EndDateSpinner.setEnabled(false);
        }
        // Set the same date since it is only 1 day competition
        EndDateSpinner.setValue(InitDateSpinner.getValue());
}//GEN-LAST:event_OneDayRadioButtonActionPerformed

    /**
     * Manages the ThreeDayRadioButton ActionPerformed.
     * @param evt
     */
    private void ThreeDayRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ThreeDayRadioButtonActionPerformed
        // Check if the second spinner is enabled
        if (EndDateSpinner.isEnabled()) {
            EndDateSpinner.setEnabled(false);
        }
        // Set the date three days after (2 days plus the actual one = 3)
        increaseCalendarDate((Date) InitDateSpinner.getValue(), EndDateSpinner, 2);

    }//GEN-LAST:event_ThreeDayRadioButtonActionPerformed

    /**
     * Manages the FiveDayRadioButton ActionPerformed.
     * @param evt
     */
    private void FiveDayRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_FiveDayRadioButtonActionPerformed
        // Check if the second spinner is enabled
        if (EndDateSpinner.isEnabled()) {
            EndDateSpinner.setEnabled(false);
        }
        // Set the date five days after (4 days plus the actual one = 3)
        increaseCalendarDate((Date) InitDateSpinner.getValue(), EndDateSpinner, 4);
}//GEN-LAST:event_FiveDayRadioButtonActionPerformed

    /**
     * Manages the OtherDayRadioButton ActionPerformed.
     * @param evt
     */
    private void OtherRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OtherRadioButtonActionPerformed
        // Check if the second spinner is enabled
        if (!EndDateSpinner.isEnabled()) {
            EndDateSpinner.setEnabled(true);
        }
        // Set the same date plus one day since it is up to the user
        Calendar aux = Calendar.getInstance();
        aux.setTime(((Date) InitDateSpinner.getValue()));
        aux.set(Calendar.DATE, aux.get(Calendar.DATE) + 1);
        EndDateSpinner.setValue(aux.getTime());
}//GEN-LAST:event_OtherRadioButtonActionPerformed

    /**
     * Manages the AddCategoryButton ActionPerformed.
     * @param evt
     */
    private void AddCategoryButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddCategoryButtonActionPerformed

        //TODO: Here prompt a Category Form to fill the propper category.

        if (AddCategoryTextField.getText().equalsIgnoreCase("")/*TODO: Verify here also if the object is already in the list */) {
            if (logger.isLoggable(Level.WARNING)) {
                logger.log(Level.WARNING, "Category already in list or null.");
            }
            return;
        }

        //TODO: Add the element in the ArrayList<>
        unsortedModel.addElement(AddCategoryTextField.getText());
        AddCategoryTextField.setText("");
        AddCategoryTextField.requestFocus();
}//GEN-LAST:event_AddCategoryButtonActionPerformed

    /**
     * Manages the DeleteCategoryButton ActionPerformed.
     * @param evt
     */
    private void DeleteCategoryButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DeleteCategoryButtonActionPerformed
        //get selected index
        int index = CategoryList.getSelectedIndex();

        //if index length is greater than 0 it means a selection done
        if (index != -1) {
            // Remove the selected index
            unsortedModel.remove(sortedModel.toUnsortedModelIndex(index));
            // Select the previous one if it is the last and the following if not
            if (unsortedModel.getSize() == index) {
                CategoryList.setSelectedIndex(unsortedModel.getSize() - 1);
            } else {
                CategoryList.setSelectedIndex(index++);
            }
        }

    // TODO: Manage correctly the multiselection deletion
//        int indexLength = CategoryList.getSelectedIndices().length;
//        int[] selectedSorted = CategoryList.getSelectedIndices();
//        int[] selectedUnsorted = sortedModel.toUnsortedModelIndices(selectedSorted);
//
//        System.out.println("Selected indices for...");
//        System.out.print("Sorted model: ");
//        for(int i:selectedSorted){
//            if(i == selectedSorted[selectedSorted.length-1]){
//                System.out.print(i+".\n");
//            } else {
//                System.out.print(i+", ");
//            }
//        }
//        System.out.print("Unsorted model: ");
//        for(int i:selectedUnsorted){
//            if(i == selectedUnsorted[selectedUnsorted.length-1]){
//                System.out.print(i+".\n");
//            } else {
//                System.out.print(i+", ");
//            }
//            System.out.println("Deleting "+i);
//            unsortedModel.remove(i);
//        }
//
//
//            //if index length is greater than 0 it means a selection done
//            if (/*indexLength > 0*/index != -1) {
//                // TODO: Manage correctly the multiselection deletion
//
//              for (int i=0;i<indexLength;i++) {
//                // Remove the selected index
//                unsortedModel.remove(sortedModel.toUnsortedModelIndex(index));
//                // Select the previous one if it is the last and the following if not
//                if (unsortedModel.getSize() == index) {
//                    CategoryList.setSelectedIndex(unsortedModel.getSize() - 1);
//                } else {
//                    CategoryList.setSelectedIndex(index++);
//                }
//              }
//            }
    }//GEN-LAST:event_DeleteCategoryButtonActionPerformed

    /**
     * Manages the EditCategoryButton ActionPerformed.
     * @param evt
     */
    private void EditCategoryButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EditCategoryButtonActionPerformed
        // First of all, get the selected index
        int index = CategoryList.getSelectedIndex();
        // Apply case where the new text has to go to the JList
        if (EditCategoryButton.getText().equalsIgnoreCase("Apply")) {
            if (EditCategoryTextField.getText().equalsIgnoreCase("")) {
                //TODO: Here a warning on what the user want to do
                // Provisional return.
                if (logger.isLoggable(Level.WARNING)) {
                    logger.log(Level.WARNING, "No input specified.");
                }
                return;
            }
            // Avoid its modification
            EditCategoryTextField.setEditable(false);
            // Add the new element to the JList
            unsortedModel.addElement(EditCategoryTextField.getText());
            // Finally adjust the TextField and the JButton
            EditCategoryTextField.setText("");
            EditCategoryTextField.setEnabled(false);
            EditCategoryButton.setText("Edit");
            CategoryList.requestFocus();
        } else {
            // Edit case where the text has to go to the TextField to be edited
            if (index != -1) { //if index is different than -1 it means a selection done
                // Get The String and copy it to the TextField
                String categoryEdition = (String) unsortedModel.getElementAt(sortedModel.toUnsortedModelIndex(index));
                EditCategoryTextField.setText(categoryEdition);
                // Remove the initial category
                unsortedModel.remove(sortedModel.toUnsortedModelIndex(index));
                // Finally adjust the TextField and the JButton
                EditCategoryTextField.setEditable(true);
                EditCategoryTextField.setEnabled(true);
                EditCategoryButton.setText("Apply");
                EditCategoryTextField.requestFocus();
            }
        }
    }//GEN-LAST:event_EditCategoryButtonActionPerformed

    /**
     * Manages the CategoryList KeyPressed.
     * @param evt
     */
    private void CategoryListKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_CategoryListKeyPressed
        int key = evt.getKeyCode();
        // If pressed the delete or the back space,
        // then act as if the delete button would have been pressed
        if (key == KeyEvent.VK_DELETE || key == KeyEvent.VK_BACK_SPACE) {
            int option = JOptionPane.showConfirmDialog(this, "Delete selected elements?");
            if (option == JOptionPane.YES_OPTION) {
                DeleteCategoryButtonActionPerformed(null);
            }

        // If pressed the enter and something selected,
        // then act as if the edit button would have been pressed
        } else if (key == KeyEvent.VK_ENTER && !CategoryList.isSelectionEmpty()) {
            EditCategoryButtonActionPerformed(null);
        }
    }//GEN-LAST:event_CategoryListKeyPressed

    /**
     * Manages the AddCategoryTextField KeyPressed.
     * @param evt
     */
    private void AddCategoryTextFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_AddCategoryTextFieldKeyPressed
        int keyCode = evt.getKeyCode();
        if (keyCode == KeyEvent.VK_ENTER) {
            AddCategoryButtonActionPerformed(null);
        }
    // else ignore key presses
    }//GEN-LAST:event_AddCategoryTextFieldKeyPressed

    /**
     * Manages the EditCategoryTextField KeyPressed.
     * @param evt
     */
    private void EditCategoryTextFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_EditCategoryTextFieldKeyPressed
        int keyCode = evt.getKeyCode();
        if (EditCategoryTextField.isEditable() && EditCategoryTextField.isEnabled() &&
                keyCode == KeyEvent.VK_ENTER) {
            EditCategoryButtonActionPerformed(null);
        }
    // else ignore key presses
    }//GEN-LAST:event_EditCategoryTextFieldKeyPressed

    /**
     * Manages the AcceptButton ActionPerformed.
     * @param evt
     */
    private void AcceptButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AcceptButtonActionPerformed
        // TODO add your handling code here: Send the edited data to the main application.

        // Check if the fields met the propper conditions to fill a Championship Class
        if (!checkFields()) {
            JOptionPane.showMessageDialog(this,
                    "One or more fields are empty.\nPlease verify all the fields.",
                    "Warning - Incomplete Fields", JOptionPane.WARNING_MESSAGE);
        } else {
            // Apply the fields to the Championship Class and close this window.
            System.out.println("Name: " + NameTextField.getText());
            System.out.print("Radio Button: ");
            if (OneDayRadioButton.isSelected()) {
                System.out.println("ONE");
            } else if (ThreeDayRadioButton.isSelected()) {
                System.out.println("THREE");
            } else if (FiveDayRadioButton.isSelected()) {
                System.out.println("FIVE");
            } else if (OtherRadioButton.isSelected()) {
                System.out.println("OTHER");
            } else {
                System.out.println("WARNING!!!");
            }
            System.out.println("Init Date: " + InitDateSpinner.getValue());
            System.out.println("End Date: " + EndDateSpinner.getValue());
            System.out.println("Region: " + RegionTextField.getText());
            System.out.println("Country: " + CountryTextField.getText());
            System.out.println("Location: " + LocationTextField.getText());
            System.out.print("Categories List: ");
            int auxSize = sortedModel.getSize() - 1;
            for (int i = 0; i < sortedModel.getSize(); i++) {
                if (i == auxSize) {
                    System.out.println(sortedModel.getElementAt(i));
                } else {
                    System.out.print(sortedModel.getElementAt(i) + ", ");
                }
            }
        }
    }//GEN-LAST:event_AcceptButtonActionPerformed

    /**
     * Manages the CancelButton ActionPerformed.
     * @param evt
     */
    private void CancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CancelButtonActionPerformed
        // TODO add your handling code here: Send a null to the main application
    }//GEN-LAST:event_CancelButtonActionPerformed

    private void InitDateSpinnerStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_InitDateSpinnerStateChanged
        // Check the changes of the spinner depending on the radiobutton selected

        // Check if the date selected is greater or equal to the actual date.
        Date today = new Date();
        Calendar aux = Calendar.getInstance();
        aux.setTime(today);
        aux.set(Calendar.HOUR, 0);
        aux.set(Calendar.MINUTE, 0);
        aux.set(Calendar.SECOND, 0);
        aux.set(Calendar.MILLISECOND, 0);
        today = aux.getTime();

        // If it is, then do nothing
        if (((Date) InitDateSpinner.getValue()).compareTo(today) < 0) {
            if (logger.isLoggable(Level.WARNING)) {
                logger.log(Level.WARNING, "The date you try to introduce is earlier than today.");
            }
            InitDateSpinner.setValue(today);
            return;
        }

        if (OneDayRadioButton.isSelected()) {
            OneDayRadioButtonActionPerformed(null);
        } else if (ThreeDayRadioButton.isSelected()) {
            ThreeDayRadioButtonActionPerformed(null);
        } else if (FiveDayRadioButton.isSelected()) {
            FiveDayRadioButtonActionPerformed(null);
        } else {
            OtherRadioButtonActionPerformed(null);
        }
}//GEN-LAST:event_InitDateSpinnerStateChanged

    private void EndDateSpinnerStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_EndDateSpinnerStateChanged
        // Only check the change of state if the spinner is enabled,
        // otherwise it will be managed by the code automatically
        
        // Check if the date selected is greater or equal to the actual date.
        if (EndDateSpinner.isEnabled()) {
            
            // Get the init date
            Date init = (Date) InitDateSpinner.getValue();
            Calendar calendar_init = Calendar.getInstance();
            calendar_init.setTime(init);
            calendar_init.set(Calendar.MILLISECOND, 0);
            System.out.println("Init: "+calendar_init.getTime()+"\nInit (milis): "+calendar_init.getTimeInMillis());

            // Get the end date
            Date end = (Date) EndDateSpinner.getValue();
            Calendar calendar_end = Calendar.getInstance();
            calendar_end.setTime(end);
            calendar_end.set(Calendar.MILLISECOND, 0);
            System.out.println("End: "+calendar_end.getTime()+"\nEnd (milis): "+calendar_end.getTimeInMillis());

            // TODO: This code needs to be reviewed. Now works but three times in a row per change??

            // Check if the second spinner is earlier than the first one
            if (((Date) InitDateSpinner.getValue()).compareTo(((Date) EndDateSpinner.getValue())) > 0) {
                // if it is earlier, throw a warning and then, turn back to
                // the same as if OtherRadioButton would have been pressed
                if (logger.isLoggable(Level.WARNING)) {
                    logger.log(Level.WARNING, "The second spinner is earlier than the first one.");
                }
                OtherRadioButtonActionPerformed(null);
            }
            // Check if the actual value is the same, two or four days in order to set the propper radiobutton.

            

            // Comparation for the same day
            if ((calendar_init.get(Calendar.DATE) == calendar_end.get(Calendar.DATE)) &&
                    (calendar_init.get(Calendar.MONTH) == calendar_end.get(Calendar.MONTH)) &&
                    (calendar_init.get(Calendar.YEAR) == calendar_end.get(Calendar.YEAR))) {
                OneDayRadioButton.setSelected(true);
                OneDayRadioButtonActionPerformed(null);
            } else if (((calendar_init.get(Calendar.DATE) + 2) == calendar_end.get(Calendar.DATE)) &&
                    (calendar_init.get(Calendar.MONTH) == calendar_end.get(Calendar.MONTH)) &&
                    (calendar_init.get(Calendar.YEAR) == calendar_end.get(Calendar.YEAR))) {
                ThreeDayRadioButton.setSelected(true);
                ThreeDayRadioButtonActionPerformed(null);
            } else if (((calendar_init.get(Calendar.DATE) + 4) == calendar_end.get(Calendar.DATE)) &&
                    (calendar_init.get(Calendar.MONTH) == calendar_end.get(Calendar.MONTH)) &&
                    (calendar_init.get(Calendar.YEAR) == calendar_end.get(Calendar.YEAR))) {
                FiveDayRadioButton.setSelected(true);
                FiveDayRadioButtonActionPerformed(null);
            }
        }


}//GEN-LAST:event_EndDateSpinnerStateChanged

    /**
     * A method to increase the number of days for the JSpinners.
     * @param baseDate - The date that has to be increased.
     * @param targetSpinner - The spinner where the date will be set on it.
     * @param increment - The increment (IN DAYS).
     */
    private void increaseCalendarDate(Date baseDate, JSpinner targetSpinner, int increment) {
        Calendar cal = new GregorianCalendar();
        cal.setTime(baseDate);
        cal.add(Calendar.DATE, increment);
        targetSpinner.setValue(cal.getTime());
    }

    /**
     * Verifies if the actual state is the one propper to fill a Championship class.
     * @return boolean true if the fields met the conditions, false otherwise.
     */
    private boolean checkFields() {
        boolean ret = false;
        // Check the name field
        if (NameTextField.getText().equalsIgnoreCase("")) {
            return ret;
        }
        // Check the Region
        if (RegionTextField.getText().equalsIgnoreCase("")) {
            return ret;
        }
        // Check the Country
        if (CountryTextField.getText().equalsIgnoreCase("")) {
            return ret;
        }
        // Check the Location
        if (LocationTextField.getText().equalsIgnoreCase("")) {
            return ret;
        }
        // Check the Categories List
        if (sortedModel.getSize() <= 0) {
            return ret;
        }

        // Else boolean=true
        ret = true;

        return ret;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                CompetitionForm dialog = new CompetitionForm(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    //TODO: This variable is an emulation for the real list of competitors and
    //categories to manage once it works as a parameters with the main window.
    private List<String> competitors = new ArrayList<String>();

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton AcceptButton;
    private javax.swing.JButton AddCategoryButton;
    private javax.swing.JTextField AddCategoryTextField;
    private javax.swing.JButton CancelButton;
    private javax.swing.JList CategoryList;
    private javax.swing.JPanel CategoryPanel;
    private javax.swing.JScrollPane CategoryScrollPane;
    private javax.swing.JLabel CountryLabel;
    private javax.swing.JLabel CountryLabel1;
    private javax.swing.JTextField CountryTextField;
    private javax.swing.JButton DeleteCategoryButton;
    private javax.swing.JButton EditCategoryButton;
    private javax.swing.JTextField EditCategoryTextField;
    private javax.swing.JLabel EndDateLabel;
    private javax.swing.JSpinner EndDateSpinner;
    private javax.swing.JRadioButton FiveDayRadioButton;
    private javax.swing.JLabel InitDateLabel;
    private javax.swing.JSpinner InitDateSpinner;
    private javax.swing.JTextField LocationTextField;
    private javax.swing.JPanel MainBodyPanel;
    private javax.swing.JLabel NameLabel;
    private javax.swing.JTextField NameTextField;
    private javax.swing.JRadioButton OneDayRadioButton;
    private javax.swing.JRadioButton OtherRadioButton;
    private javax.swing.JPanel RadioButtonPanel;
    private javax.swing.JLabel RegionLabel;
    private javax.swing.JTextField RegionTextField;
    private javax.swing.JRadioButton ThreeDayRadioButton;
    private javax.swing.ButtonGroup buttonGroup1;
    // End of variables declaration//GEN-END:variables
}
